package io.github.center.config.advice;

import io.github.common.Result;
import io.github.common.util.Jsons;
import org.springframework.core.MethodParameter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.Collections;

/**
 * rest controller的切面增强，只切对应包下面的controller否则knife文档生成会出问题
 *
 * @author haijun
 * @version 1.0.0
 * @email "1424132610@qq.com"
 * @date 2024.10.19 11:22
 * @since 1.0.0
 */
@RestControllerAdvice("io.github.center.controller")
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GlobalResultAdvice implements ResponseBodyAdvice<Object> {


    /**
     * Supports
     *
     * @param methodParameter method parameter
     * @param aClass          a class
     * @return the boolean
     * @since 1.0.0
     */
    @Override
    public boolean supports(@NotNull MethodParameter methodParameter,
                            @NotNull Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    /**
     * Before body write
     *
     * @param body               o
     * @param methodParameter    method parameter
     * @param mediaType          media type
     * @param aClass             a class
     * @param serverHttpRequest  server http request
     * @param serverHttpResponse server http response
     * @return the object
     * @since 1.0.0
     */
    @Override
    public Object beforeBodyWrite(Object body,
                                  @NotNull MethodParameter methodParameter,
                                  @NotNull MediaType mediaType,
                                  @NotNull Class<? extends HttpMessageConverter<?>> aClass,
                                  @NotNull ServerHttpRequest serverHttpRequest,
                                  @NotNull ServerHttpResponse serverHttpResponse) {
        return this.warp(body, serverHttpResponse);
    }

    /**
     * Warp
     *
     * @param body body
     * @return the object
     * @since 1.0.0
     */
    private Object warp(Object body, @NotNull ServerHttpResponse serverHttpResponse) {
        if (body instanceof Result) {
            return body;
        }
        Result<Object> result = Result.success(body);
        if (body instanceof String) {
            serverHttpResponse.getHeaders()
                    .put(HttpHeaders.CONTENT_TYPE, Collections.singletonList(MediaType.APPLICATION_JSON_VALUE));
            return Jsons.toJson(result);
        }
        return result;
    }
}
